package com.wyw.hemerocallis.config;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Feign 调用时，把Header也传递到服务提供方
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@Configuration
public class FeignConfig {

    /**
     * 给Feign 配置请求拦截器
     * RequestInterceptor是我们提供给open-feign的请求拦截器，把Header信息传递
     * @return
     */
    @Bean
    public RequestInterceptor headerInterceptor() {
        return template -> {
            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(null != attributes) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if(null != headerNames) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        //不可能把当前的请求content-length 传递到下游服务提供方，这样是不可以的
                        //请求可能一直返回不了，或者请求响应数据被截断
                        if(!name.equalsIgnoreCase("content-length")) {
                            //这里的template就是RestTemplate
                            template.header(name, values);
                        }
                    }
                }
            }

        };

    }
}
